package com.java1234.jxc.realm;

import com.java1234.jxc.beans.SysMenu;
import com.java1234.jxc.beans.SysRole;
import com.java1234.jxc.beans.SysUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by Administrator on 2018/3/17.
 */
public class MyRealm extends AuthorizingRealm{

    @Autowired
    Dao dao;

    /**
     * 权限认证
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String userName = (String) SecurityUtils.getSubject().getPrincipal();
        SysUser user = dao.fetch(SysUser.class, Cnd.where("userName", "=", userName));
        dao.fetchLinks(user,null);
        List<SysRole> roleList = user.getRoles();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Set<String> roles = new HashSet<>();
        for (SysRole role:roleList){
            roles.add(role.getName());
            dao.fetchLinks(role,"^menus$");
            List<SysMenu> menuList =role.getMenus();
            for (SysMenu menu:menuList){
                info.addStringPermission(menu.getName());
            }
            info.setRoles(roles);
        }
        return info;
    }

    /**
     * 身份认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String userName = (String)token.getPrincipal();   // 获取用户名
        SysUser user = dao.fetch(SysUser.class, Cnd.where("userName","=",userName));
        if (user!=null){
            AuthenticationInfo authInfo = new SimpleAuthenticationInfo(user.getUserName(),user.getPassword(),this.getName());
            return authInfo;
        }else{

            return null;
        }
    }
}
